﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.Web.Mvc;

namespace IModelBinderSample
{
    public class DateTimeModelBinder : IModelBinder
    {
        public string Format { get; private set; }

        public DateTimeModelBinder(string format)
        {
            this.Format = format;
        }

        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).RawValue;
            if (value is string)
            {
                return DateTime.ParseExact((string)value, this.Format, null);
            }
            else
            {
                return value;
            }
        }
    }

    public class DateTimeAttribute : CustomModelBinderAttribute
    {
        public string Format { get; private set; }

        public DateTimeAttribute(string format)
        {
            this.Format = format;
        }

        public override IModelBinder GetBinder()
        {
            return new DateTimeModelBinder(this.Format);
        }
    }

}